package com.hwq.sql.script.controller;

import com.hwq.sql.script.exception.ClientException;
import com.hwq.sql.script.model.vo.ResultVO;
import com.hwq.sql.script.utils.HttpUtil;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Controller
public class AdviceController implements ErrorController {

    /**
     * 当出现错误时，转发到哪个路由
     */
    @Override
    public String getErrorPath() {
        return "/error";
    }

    /**
     * 处理 404 找不到路由的异常
     */
    @GetMapping("/error")
    @ResponseBody
    public ResultVO<Object> error() {
        return HttpUtil.failure("接口地址不存在", "NOT FUND URI");
    }

    /**
     * 全局异常捕获，当程序出现异常时被调用
     * @param ex 捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultVO<Object> error(Exception ex) {
        if (ex instanceof ClientException) {
            return HttpUtil.failure(ex.getMessage());
        } else {
            return HttpUtil.error("请求服务器失败，请稍后再试！", ex.getMessage());
        }
    }
}
